import Router from 'koa-router'
import { GET } from '../../common/Request'
import { User, Article } from '../../service'
import CONFIG from '../../config'
const router = new Router();

router.post('/login', async(ctx)=>{
    let id = ctx.query.id
    let code = ctx.query.code

    if(id != null){
        let user = await User.get(id);
        if(user != null){
            user.nickname = ctx.request.body.nickName,
            user.avatarUrl = ctx.request.body.avatarUrl
            user.country = ctx.request.body.country
            user.province = ctx.request.body.province
            user.city = ctx.request.body.city
            user.gender = ctx.request.body.gender
            user.save()
            return user
        }
    }

    if(code != null){
        let data = await GET(`https://api.weixin.qq.com/sns/jscode2session?appid=${CONFIG.APPID}&secret=${CONFIG.SECRET}&js_code=${code}&grant_type=authorization_code`)
        if(data.errcode){ throw { errMsg : '无法获取APP Token' } }
        let user = await User.get(data.openid);
        if(user != null){
            user.session = data.session_key
            user.nickname = ctx.request.body.nickName,
            user.avatarUrl = ctx.request.body.avatarUrl
            user.country = ctx.request.body.country
            user.province = ctx.request.body.province
            user.city = ctx.request.body.city
            user.gender = ctx.request.body.gender
            user.save()
        }else{
            user = {
                id : data.openid,
                session : data.session_key,
                code : Math.random().toString(36).substr(2),
                nickname : ctx.request.body.nickName,
                avatarUrl : ctx.request.body.avatarUrl,
                country : ctx.request.body.country,
                province : ctx.request.body.province,
                city : ctx.request.body.city,
                gender : ctx.request.body.gender
            }
            await User.save(user)
        }
        return user
    }
    throw { errMsg : '无法获取APP Token' }
})

router.get('/info', async(ctx)=>{
    return await User.get(ctx.query.user)
})

router.get('/count', async(ctx) => {
    let countCountry = await User.countCountry()
    let countCity = await User.countCity()
    let countUser = await User.count()
    let count = await Article.count()
    return {countCountry, countCity, countUser, count}
})

export default router
